package com.wlstock.funi.utils;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TimeUtils {

	public static enum TIME_PERIOD{
		MONTH,
		DAY,
		HOUR,
		MIN,
		SEC
	}

	/**
	 * 获取开始时间跟结束时间中的所有时间list
	 * @param a 开始时间,格式为yyyy.MM.dd
	 * @param b 结束时间,格式为yyyy.MM.dd
	 * @return
	 */
	
    public static List<String> getDays(String a, String b) {
        List<String> days = new ArrayList<String>();// 日期集合
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        try {
            long end = sdf.parse(b).getTime();
            long begin = sdf.parse(a).getTime();
            while (begin <= end) {
                Date day = new Date();
                day.setTime(begin);
                begin += 3600 * 24 * 1000;
                days.add(sdf.format(day));
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return days;
    }
	
	public static String parseDateDistance(String createTime){    
        try {
            String ret = null;
            //?这里有问题
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = sdf.parse(createTime);
            ret = parseDateDistance(date);
            	return ret;
            } catch (Exception e) {
            	e.printStackTrace();
            }
        return null;
    }

	public static String parseDateDistance(Date date) {
		String ret;
		long create = date.getTime();
		Calendar now = Calendar.getInstance();
		long ms  = 1000*(now.get(Calendar.HOUR_OF_DAY)*3600+now.get(Calendar.MINUTE)*60+now.get(Calendar.SECOND));//毫秒数
		long ms_now = now.getTimeInMillis();
		if(ms_now-create<ms){
		    ret = "今天";
		}else if(ms_now-create<(ms+24*3600*1000)){
		    ret = "昨天";
		}else if(ms_now-create<(ms+24*3600*1000*2)){
		    ret = "前天";
		}else{
		    ret= "更早";
		}
		return ret;
	}
	
//	2015-10-21T13:36:03.14
	public static CharSequence parseHHMM(Date dateStr){
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		return sdf.format(dateStr);
	}
	
	public static String getCurrentHHMM(){
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		return sdf.format(new Date());
	}
	
	public static String patternDate(String dateStr){
		Pattern compile = Pattern.compile("[0-9][0-9]T[0-9][0-9]:");
		Matcher matcher = compile.matcher(dateStr);
		while (matcher.find()) {
			String temp = dateStr.substring(matcher.start(), matcher.end());
			String temp2 = temp.replace("T", " ");
			dateStr = dateStr.replaceAll(temp, temp2);
		}
		return dateStr;
	}
	
	/**
	 * 在监控时间内进行止损
	 * @return
	 */
	public static boolean isInDetectTime(){
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		try {
			Date detectMorBegin = sdf.parse("10:40");
			Date detectMorEnd = sdf.parse("11:10");
			Date detectMiddleBegin = sdf.parse("14:30");
			Date detectMiddleEnd = sdf.parse("15:00");
			Date nowDate   = sdf.parse(sdf.format(new Date()));
			boolean isInMorning = (nowDate.getTime()-detectMorBegin.getTime())>0 && (nowDate.getTime()-detectMorEnd.getTime())<0;
			boolean isInMiddle  = (nowDate.getTime()-detectMiddleBegin.getTime())>0 && (nowDate.getTime()-detectMiddleEnd.getTime())<0;
			return isInMorning || isInMiddle;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	
	public static boolean isDayInRange(Date beginTime, Date endTime,Date curDate){
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
		return isTimeInRange("MM-dd", sdf.format(beginTime), sdf.format(endTime), curDate);
	}
	
	public static boolean isHourInRange(String beginTime, String endTime,Date curDate){
		return isTimeInRange("HH:mm", beginTime, endTime, curDate);
	}
	
	public static boolean isTimeInRange(String pattern,String beginTime, String endTime,Date curDate){
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			Date detectBegin = sdf.parse(beginTime);
			Date detectEnd = sdf.parse(endTime);
			Date nowDate = sdf.parse(sdf.format(curDate));
			boolean isInRange = (nowDate.getTime()-detectBegin.getTime())>=0 && (nowDate.getTime()-detectEnd.getTime())<=0;
			return isInRange;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 检测回撤的时间
	 * @return
     */
	public static boolean isInNeedBackTime() {
		return isHourInRange("10:29","14:58",new Date());
	}

	public static Date getDateByMonthOffset(Date date, int offset) {
		Calendar cl = Calendar.getInstance();
        cl.setTime(date);
        cl.add(Calendar.MONTH, offset);
        return cl.getTime();
	}

	public static Date getDateByDayOffset(Date date, int offset){
		Calendar cl = Calendar.getInstance();
		cl.setTime(date);
		cl.add(Calendar.DATE, offset);
		return cl.getTime();
	}

	public static Date getDateByHourOffset(Date date, int offset){
		Calendar cl = Calendar.getInstance();
		cl.setTime(date);
		cl.add(Calendar.HOUR, offset);
		return cl.getTime();
	}


	/**
	 * 判断两个时间的相距绝对值是否在某个固定值内,如果周期是小时,则判断的是2个时间的相距绝对值是否在range这个范围内
	 * 这个用来确定数据库里面的某些数据是否是最新的数据
	 * @param d1
	 * @param d2
	 * @param period
	 * @param range
     * @return
     */
	public static boolean  isDateInPeriodRange(Date d1, Date d2, TIME_PERIOD period,long range){
		long dis = dateDiff(d1, d2, period);
		if (dis == -1)
			return false;
		return dis < range;
	}

	/**
	 * 获取2个时间之间的周期相距的绝对值(传入的时间没先后所谓),如果周期是小时,则是2个时间相差多少个小时,
	 * 正确的情况下返回的是一个大于0的数,如果等于-1,则表示出错,或者无法计算这个周期
	 * @param d1
	 * @param d2
	 * @param period
     * @return
     */
	public static long dateDiff(Date d1, Date d2, TIME_PERIOD period){
		if (d1==null || d2 ==null)
			return -1;
		long day = 0;
		long hour = 0;
		long min = 0;
		long sec = 0;
		long time1 = d1.getTime();
		long time2 = d2.getTime();
		long diff ;
		if(time1<time2) {
			diff = time2 - time1;
		} else {
			diff = time1 - time2;
		}
		day = diff / (24 * 60 * 60 * 1000);
		hour = (diff / (60 * 60 * 1000) - day * 24);
		min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
		sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
		switch (period){
			case DAY:
				return day;
			case HOUR:
				return hour;
			case MIN:
				return min;
			case SEC:
				return sec;
			default:
				return -1;
		}
	}

	/**
	 * 获取2个时间之间的周期相距的绝对值(传入的时间没先后所谓),如果周期是小时,则是2个时间相差多少个小时,
	 * 正确的情况下返回的是一个大于0的数,如果等于-1,则表示出错,或者无法计算这个周期
	 * @param str1
	 * @param str2
	 * @param period
	 * @return
	 */
	public static long dateDiff(String str1, String str2, TIME_PERIOD period) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date one;
		Date two;
		try {
			one = df.parse(str1);
			two = df.parse(str2);
			return dateDiff(one, two, period);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return -1;
	}

	/**
	 * * 取2个时间段之间的日期的间距绝对值,除去周末,字符串格式化为"yyyy-MM-dd"
	 * @param startDateStr
	 * @param endDateStr
     * @return
     */
	public static long dateDiff(String startDateStr, String endDateStr) {
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		long days1 = 0l;
		try {
			Date endDate = sd.parse(endDateStr);
			Date startDate = sd.parse(startDateStr);
			return dateDiff(startDate, endDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return days1;
	}

	/**
	 * 取2个时间段之间的日期的间距绝对值,除去周末
	 * @param startDate
	 * @param endDate
     * @return
     */
	public static  long dateDiff(Date startDate, Date endDate){
		if (startDate.getTime() > endDate.getTime()){
			Date tmpDate = startDate;
			startDate    = endDate;
			endDate      = tmpDate;
		}
		GregorianCalendar endGC = new GregorianCalendar();
		long times, days1 = 0l;

		times = endDate.getTime() - startDate.getTime();
		long days = times / (1000 * 24 * 60 * 60);// 间隔天数
		days1 = (days / 7) * 5;// 整周天数
		long days2 = days % 7;// 除去整周，余下天数
		endGC.setTime(endDate);
		int endweekDay = endGC.get(Calendar.DAY_OF_WEEK);// 结束在周几
		if (endweekDay == 1) {// 结束在周日
			days1 += days2 > 1 ? days2 - 1 : 0;
		} else if (endweekDay == 7) {// 结束在周六
			days1 += days2 == 6 ? 5 : days2;
		} else if (days2 == 0) {// 一个工作日
			days1 += 1;
		} else if (endweekDay - days2 == 1) {// 开始在周日
			days1 += days2;
		} else if (endweekDay - days2 <= 0) {// 开始在周六及以上，即包含周六日，需减一天
			days1 += days2 - 1;
		} else {// 其他时候，因为days为间隔时间，需加一天
			days1 += days2 + 1;
		}
		//调整一下日期,同一天返回应该是0
		if (days1 > 0)
			days1 = days1 - 1;
		return days1;

	}


}
